package com.liveinstars.common.aspect;

import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础切面支持服务 解析注解中SPEL表达式
 * Created by guoyanjiang on 2018/5/7.
 */
@Service
public class BaseAspectSupportService {
    ParameterNameDiscoverer parameterNameDiscoverer;
    ExpressionParser expressionParser;

    @PostConstruct
    public void init() {
        parameterNameDiscoverer = new StandardReflectionParameterNameDiscoverer();
        expressionParser = new SpelExpressionParser();
    }

    /*
        获取参数名的前提（任选其一）
        1、jdk1.8 编译时添加`-parameters`参数(从MethodParameters中获取) 目前用这个
        2、启用调试模式`-g`(从LocalVariableTable中获取)
        参考：ParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
     */
    public String getSpelValue(String key, Method method, Object[] args) {
        String[] paramsNames = parameterNameDiscoverer.getParameterNames(method);
        StandardEvaluationContext context = new StandardEvaluationContext(null);
        for (int i = 0; i < paramsNames.length; i++) {
            context.setVariable(paramsNames[i], args[i]);
        }
        Expression expression = expressionParser.parseExpression(key);
        return expression.getValue(context, String.class);
    }

    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext ctx = new StandardEvaluationContext();
        ctx.setVariable("uid", 12345);
        Map map = new HashMap();
        map.put("a", "aa");
        map.put("b", "bb");
        ctx.setVariable("params", map);
        System.out.println(parser.parseExpression("'bbs_'+#uid+'_detail'").getValue(ctx));
        System.out.println(parser.parseExpression("#params['a']").getValue(ctx));
        System.out.println(parser.parseExpression("#params['c']==null?'空':'不空'").getValue(ctx));

    }
}
